package kmjxc

import (
	"database/sql"
	"time"

	_ "github.com/alexbrainman/odbc"
	"github.com/axgle/mahonia"
)

//SpePriceSoldItem 特价销售明细
type SpePriceSoldItem struct {
	ItemNo      string
	ItemSubno   string
	ItemName    string
	UnitNo      string
	DiaplayFlag bool
	SalePrice   float64
	OldPrice    float64
	SpePrice    float64
	SoldQnty    float64
	StartDate   time.Time
	EndDate     time.Time
	Other3      string
	BranchNo    string
	Price       float64
}

//GetSpePriceSoldItems 获取特价销售明细
func GetSpePriceSoldItems(supcustNo string, start time.Time, end time.Time) []*SpePriceSoldItem {
	var items []*SpePriceSoldItem

	conn, err := sql.Open("odbc", KMJXCConnStr)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	//todo 无论结束与否 都能算该特价信息下的实际销售 结合折扣销售进行统计
	stmt, err := conn.Prepare(`SELECT  pos.item_no,info.item_subno,info.item_name,info.unit_no,info.display_flag,case when EXISTS (SELECT sale_price from bi_t_item_price where bi_t_item_price.item_no = info.item_no and bi_t_item_price.branch_no = pos.branch_no AND sale_price > 0 ) then (select sale_price from bi_t_item_price where bi_t_item_price.item_no = info.item_no and bi_t_item_price.branch_no = pos.branch_no) else Max(info.sale_price) end AS sale_price,pos.old_price,pos.spe_price,pos.discount,pos.sold_qnty,pos.start_date,pos.end_date,pos.other3,pos.branch_no,info.price FROM pos_t_spec_price pos,bi_t_item_info info WHERE ( pos.item_no = info.item_no) and ( pos.start_date between '2016-5-1 0:0:0.000' and '2016-5-31 23:59:59.997' ) and ( info.item_no like '%' ) and ( info.item_subno like '%' ) and ( info.item_name like '%' ) and ( info.item_clsno like '%' ) and ( pos.special_type <> 'C' ) and ( info.sup_no = ?) and ( pos.sold_qnty <> 0 ) GROUP BY pos.item_no,info.item_subno,info.item_name,info.unit_no,info.item_size,info.item_clsno,info.item_brand,info.item_brandname,info.display_flag,pos.special_type,pos.old_price,pos.spe_price,pos.discount,pos.sale_qnty,pos.sold_qnty,pos.start_date,pos.end_date,pos.other1,pos.other2,pos.other3,pos.branch_no,info.price,info.item_no`)
	if err != nil {
		panic(err)
	}
	defer stmt.Close()
	row, _ := stmt.Query(supcustNo)
	defer row.Close()
	dec := mahonia.NewDecoder("gbk")
	for row.Next() {
		var item SpePriceSoldItem
		row.Scan(&item.ItemName, &item.ItemSubno, &item.ItemName, &item.UnitNo, &item.DiaplayFlag, &item.SalePrice, &item.OldPrice, &item.SpePrice, nil, &item.SoldQnty, &item.StartDate, &item.EndDate, &item.Other3, &item.BranchNo, &item.Price)
		item.ItemName = dec.ConvertString(item.ItemName)
		items = append(items, &item)
	}
	return items
}
